<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button type="primary" size="mini" @click="showAddDialog"
        >添加角色</el-button
      >

      <!-- 列表 -->
      <el-table :data="rolesData" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :gutter="20"
              v-for="item of scope.row.children"
              :key="item.id"
            >
              <!-- 一级权限 -->
              <el-col :span="4">
                <el-tag closable @close="removeRightById(scope.row, item.id)">
                  {{ item.authName }}</el-tag
                >
              </el-col>
              <el-col :span="20">
                <!-- 二级权限 -->
                <el-row v-for="subItem of item.children" :key="subItem.id">
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, subItem.id)"
                    >
                      {{ subItem.authName }}</el-tag
                    >
                  </el-col>

                  <!-- 三级权限 -->
                  <el-col :span="16">
                    <el-tag
                      closable
                      type="warning"
                      v-for="thirdItem of subItem.children"
                      :key="thirdItem.id"
                      @close="removeRightById(scope.row, thirdItem.id)"
                    >
                      {{ thirdItem.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="prop" label="操作" width="175">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>

            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRoles(scope.row.id)"
            ></el-button>

            <!-- 分配权限 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="info"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      class="setRightDialogHeight"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsData"
        show-checkbox
        default-expand-all
        :default-checked-keys="defkeys"
        :props="rightsProps"
        node-key="id"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色对话框 -->
    <el-dialog
      :title="rolesTit"
      :visible.sync="rolesDialogVisible"
      width="50%"
      @close="rolesDialogClosed"
    >
      <el-form
        :model="rolesForm"
        :rules="rolesFormRules"
        ref="rolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" v-if="isRoles" @click="addRoles"
          >确 定</el-button
        >
        <el-button type="primary" v-else @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getRolesList()
  },
  data() {
    return {
      // 所有角色列表数据
      rolesData: [],
      // 控制分配权限对话框的显示隐藏
      setRightDialogVisible: false,
      // 所有权限数据
      rightsData: [],
      // 树形控件的属性绑定对象
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点id值的数组
      defkeys: [],
      // 当前即将分配权限的ID
      roleId: '',
      // 角色对话框的显示状态
      rolesDialogVisible: false,
      // 用户的信息
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 用户校验规则
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: '2', max: '10', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      rolesTit: '',
      isRoles: false,
      // 编辑的id
      rolesId: ''
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.rolesData = res.data
      }
    },

    // 根据id删除权限
    async removeRightById(role, rightsId) {
      // 弹出确认对话框
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        this.$message('用户取消了删除操作')
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightsId}`
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        } else {
          this.$message.success(res.meta.msg)
          role.children = res.data
        }
      }
    },

    // 删除角色
    async delRoles(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        this.$message('用户取消了删除操作')
      } else {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        } else {
          this.$message.success(res.meta.msg)
          this.getRolesList()
        }
      }
    },

    // 显示分配权限对话框
    async showSetRightDialog(row) {
      this.roleId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.rightsData = res.data

        // 递归获取三级节点的id
        this.getLeafKeys(row, this.defkeys)
        this.setRightDialogVisible = true
      }
    },

    // 获取三级权限的id
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },

    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defkeys = []
    },

    // 分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
        this.getRolesList()
        this.setRightDialogVisible = false
      }
    },

    // 显示添加角色对话框
    showAddDialog() {
      this.rolesForm = {}
      this.isRoles = true
      this.rolesTit = '添加角色'
      this.rolesDialogVisible = true
    },

    // 关闭角色对话框
    rolesDialogClosed() {
      this.$refs.rolesFormRef.resetFields()
    },

    // 添加角色
    addRoles() {
      this.$refs.rolesFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请输入完整的信息')
        } else {
          const { data: res } = await this.$http.post('roles', this.rolesForm)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          } else {
            this.$message.success(res.meta.msg)
            this.getRolesList()
            this.rolesDialogVisible = false
          }
        }
      })
    },

    // 显示编辑角色
    async showEditDialog(id) {
      this.isRoles = false
      this.rolesId = id
      this.rolesTit = '编辑角色'
      const { data: res } = await this.$http.get(`roles/${id}`)
      this.rolesForm = res.data
      this.rolesDialogVisible = true
    },

    // 编辑角色
    editRoles() {
      this.$refs.rolesFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请输入完整的信息')
        } else {
          const { data: res } = await this.$http.put(
            `roles/${this.rolesId}`,
            this.rolesForm
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          } else {
            this.getRolesList()
            this.rolesDialogVisible = false
            this.$message.success(res.meta.msg)
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
</style>
